package com.museum.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.museum.base.BaseApiService;
import com.museum.base.BaseResponse;
import com.museum.core.utils.RedisUtil;
import com.museum.entity.DO.Role;
import com.museum.entity.DO.RolePermission;
import com.museum.entity.DO.UserRole;
import com.museum.entity.DTO.RedisInfo.UserMessage;
import com.museum.entity.DTO.role.RoleAdd;
import com.museum.entity.DTO.role.RoleShow;
import com.museum.entity.DTO.role.RoleUpdate;
import com.museum.mapper.PermissionMapper;
import com.museum.mapper.RoleMapper;
import com.museum.mapper.RolePermissionMapper;
import com.museum.mapper.UserRoleMapper;
import com.museum.service.impl.admin.AdminRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description:
 * @ClassName museum
 * @Author: 王瑞文
 * @Date: 2020/12/26 17:37
 */
@Service
public class RoleService extends BaseApiService<JSONObject> {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PermissionService permissionService;

    /**
     * 获取所有角色信息
     *
     * @param current
     * @param limit
     * @return
     */
    public BaseResponse<JSONObject> getAllRole(HttpServletRequest request, Integer current, Integer limit) {
        String token = request.getHeader("Authorization");
        String value = redisUtil.getString(token);
        UserMessage userMessage = JSONObject.parseObject(value, UserMessage.class);
        Integer areaNumber = userMessage.getAreaNumber();
        List<String> remove = new ArrayList<>();
        List<Integer> canUsePermissionIDs = permissionMapper.getCanUsePermissionIDs();
        for (Integer canUsePermissionID : canUsePermissionIDs) {
            if (permissionMapper.getParentIdByPermissionIds(canUsePermissionID).size() != 0)
                remove.add(String.valueOf(canUsePermissionID));
        }
//        Integer userId = userMessage.getUserId();
        List<RoleShow> roleShows = new ArrayList<>();
        Page page = new Page(current, limit);
        roleMapper.selectPage(page, new QueryWrapper<Role>().eq("area_number", areaNumber));
//             .ne("role_id", userRoleMapper.selectOne(new QueryWrapper<UserRole>().eq("user_id", userId)).getRoleId())
        //获得所有的角色(不包括系统级别)
        List<Role> roles = page.getRecords();
        //把系统级别的添加进去
        List<Role> roles1 = roleMapper.selectList(new QueryWrapper<Role>().eq("level", 0));
        for (Role role : roles1) {
            roles.add(role);
        }

        //将每一个权限递归 找到他所有的权限  列出权限树
        for (Role role : roles) {
            RoleShow roleShow = new RoleShow();
            BeanUtils.copyProperties(role, roleShow);
            Integer roleId = roleShow.getRoleId();

            List<String> strings = rolePermissionMapper.selectPermissionIdsByRoleIdForUpdate(roleId, role.getAreaNumber());

            List<String> permissionsId = new ArrayList<>();
            if (strings.size() != 0)
                permissionsId = AdminRoleService.remove(strings, remove);
            roleShow.setPermissionIds(permissionsId);
            roleShows.add(roleShow);
        }


        JSONObject object = new JSONObject();
        System.out.println(roleShows);
        object.put("roles", roleShows);
        object.put("total", page.getTotal());
        return setResultSuccess(object);
    }

    public boolean isExit(Integer roleId) {
        int count = userRoleMapper.selectCount(new QueryWrapper<UserRole>().eq("role_id", roleId));
        if (count == 0) {
            return false;
        }
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 删除劫色
     *
     * @param roleId
     * @return
     */
    public BaseResponse<JSONObject> deleteRole(Integer roleId) {
        Role role = roleMapper.selectById(roleId);
        if (null == role) return setResultNotFound("没有该角色，删除失败！");
        if (role.getLevel() != 1) return setResultError("系统角色，无法删除！");
        if (isExit(roleId))
            return setResultError("已有分配用户，无法删除！");
        else {
            rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));
            return toDaoResult(roleMapper.delete(new QueryWrapper<Role>().eq("role_id", roleId))) ? setResultSuccess("删除成功！") : setResultError("删除失败！");
        }
    }

    /**
     * 给角色分配权限
     *
     * @param roleUpdate
     * @return
     */
    public BaseResponse<JSONObject> doAssign(RoleUpdate roleUpdate) {
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdate, role);
        roleMapper.updateById(role);
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleUpdate.getRoleId()));
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(role.getRoleId());
        rolePermission.setPermissionId(999);
        rolePermissionMapper.insert(rolePermission);
        String[] permissionId = roleUpdate.getPermissionId();

        List<Integer> tree = new ArrayList<>();
        for (String s : permissionId) {
            tree = permissionService.findIDFather(tree, Integer.parseInt(s));
        }
        Set<Integer> set = new HashSet<>();
        for (Integer integer : tree) {
            set.add(integer);
        }
        addPermission(role.getRoleId(), set);
        return setResultSuccess("修改成功！");
    }

    /**
     * 添加角色
     *
     * @param roleAdd
     * @return
     */
    public BaseResponse<JSONObject> addRole(HttpServletRequest request, RoleAdd roleAdd) {
        String token = request.getHeader("Authorization");
        String value = redisUtil.getString(token);
        UserMessage userMessage = JSONObject.parseObject(value, UserMessage.class);
        if (userMessage == null) return setResultError("网络异常！");
        Integer areaNumber = userMessage.getAreaNumber();


        Role role = new Role();
        BeanUtils.copyProperties(roleAdd, role);
        role.setAreaNumber(areaNumber);
        roleMapper.insert(role);

        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(role.getRoleId());
        rolePermission.setPermissionId(999);
        rolePermissionMapper.insert(rolePermission);
        String[] permissionId = roleAdd.getPermissionId();
        List<Integer> tree = new ArrayList<>();
        for (String s : permissionId) {
            tree = permissionService.findIDFather(tree, Integer.parseInt(s));
        }
        System.out.println(tree);
        Set<Integer> set = new HashSet<>();
        for (Integer integer : tree) {
            set.add(integer);
        }

        addPermission(role.getRoleId(), set);
        return setResultSuccess("添加成功！");
    }

    //role_permission 表添加数据
    public void addPermission(Integer roleId, Set<Integer> permissions) {
        for (Integer permission : permissions) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permission);
            rolePermissionMapper.insert(rolePermission);
        }
    }

}
